package com.yz.httpclient;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * HttpClientManager管理
 *
 * @author Administrator
 * @since 2016/8/8
 */
public class HttpClientManager {

    private static HttpClientBuilder httpClientBuilder = null;
    private static CloseableHttpClient closeableHttpClient = null;

    private HttpClientManager() {
        // 创建连接管理器
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
        // 设置全局的连接超时时间
        // 整个连接池的最大连接数
        connMgr.setMaxTotal(200);
        // 每个路由的最大连接数
        connMgr.setDefaultMaxPerRoute(200);
        // 创建HttpClientBuilder并设置连接管理器
        httpClientBuilder = HttpClients.custom().setConnectionManager(connMgr);
    }

    public static synchronized CloseableHttpClient getCloseableHttpClient() {
        if (closeableHttpClient == null) {
            new HttpClientManager();
            closeableHttpClient = httpClientBuilder.build();
        }
        return closeableHttpClient;
    }

}
